package com.hayukleung.voiceclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;

import com.hayukleung.base.BaseActivity;
import com.hayukleung.task.GetData;
import com.hayukleung.task.StartNetTask;
import com.hayukleung.task.UICallback;
import com.hayukleung.util.Constants;
import com.hayukleung.util.LogMgr;
import com.hayukleung.util.Util;

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MessageActivity extends BaseActivity
{
  private final static String TAG = "MessageActivity";
  private Button btnSend;
  private LinearLayout llPlay;

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    /*
     * UDP server to receive latest files list in server
     */
    new Thread()
    {
      public void run()
      {
        UDPServer.message = MessageActivity.this;
        try
        {
          UDPServer.openServer();
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    }.start();
  }

  @Override
  public void setContentView()
  {
    super.setContentView();
    setContentView(R.layout.activity_message);
  }

  @Override
  public void initWidgets()
  {
    super.initWidgets();
    btnSend = (Button) findViewById(R.id.message$btnSend);
    btnSend.setOnTouchListener(new ListenerSend());
    llPlay = (LinearLayout) findViewById(R.id.message$llPlay);
  }

  int count = 0;

  @Override
  public boolean onKeyUp(int keyCode, KeyEvent event)
  {
    if (1 == count)
    {
      System.exit(0);
      return false;
    }
    if (KeyEvent.KEYCODE_BACK == keyCode)
    {
      Util.showToast(this, getString(R.string.click_again_to_exit));
      count++;
      return false;
    }
    return super.onKeyUp(keyCode, event);
  }

  private void upload(String filename)
  {
    /*
     * upload token: [upload,filesize,username]
     */
    try
    {
      Socket socket = new Socket(Constants.SERVER_IPV4, Constants.SERVER_TCP_PORT_INT);
      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();
      String request = Constants.REQ_UPLOAD + Constants.COMMA + 
          (new File(Constants.BASE_DIR + "/" + filename).length()) + 
          Constants.COMMA + MainActivity.username;
      LogMgr.writeLog(TAG, request, LogMgr.INFO);
      out.write(request.getBytes());
      out.flush();
      // receive ok
      byte[] reply = new byte[10];
      in.read(reply);
      // start upload file
      FileInputStream fin = new FileInputStream(new File(Constants.BASE_DIR
          + "/" + filename));
      int len = 0;
      byte[] temp = new byte[1024];
      while (-1 != (len = fin.read(temp)))
      {
        out.write(temp, 0, len);
        out.flush();
      }
      fin.close();
      socket.close();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

  }

  private class ListenerSend implements OnTouchListener
  {
    private MediaRecorder recorder = new MediaRecorder();
    private String filename;

    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
      if (MotionEvent.ACTION_DOWN == event.getAction())
      { // push button
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        filename = new Date().getTime() + ".3gp";
        Util.mkdirIfNotExist(Constants.BASE_DIR);
        LogMgr.writeLog(TAG, "new file->" + Constants.BASE_DIR + "/" + filename, LogMgr.INFO);
        recorder.setOutputFile(Constants.BASE_DIR + "/" + filename);
        try
        {
          recorder.prepare();
          recorder.start();
        }
        catch (IllegalStateException e)
        {
          e.printStackTrace();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
      }
      else if (MotionEvent.ACTION_UP == event.getAction())
      { // pop button
        if (null == recorder)
        {
          return true;
        }

        // recorder.stop();
        // recorder.release();
        // recorder = null;
        recorder.stop();
        recorder.reset();

        // add button
        LinearLayout layout = new LinearLayout(MessageActivity.this);
        TextView text = new TextView(MessageActivity.this);
        Button button = new Button(MessageActivity.this);
        text.setText(MainActivity.username + ": ");
        button.setText(getString(R.string.play));
        final String PLAY_SOURCE = Constants.BASE_DIR + "/" + filename;
        button.setOnClickListener(new OnClickListener()
        {
          @Override
          public void onClick(View v)
          {
            MediaPlayer player = new MediaPlayer();
            if (player.isPlaying())
            {
              player.reset();
            }
            try
            {
              player.setDataSource(PLAY_SOURCE);
            }
            catch (IllegalArgumentException e)
            {
              e.printStackTrace();
            }
            catch (IllegalStateException e)
            {
              e.printStackTrace();
            }
            catch (IOException e)
            {
              e.printStackTrace();
            }
            try
            {
              player.prepare();
            }
            catch (IllegalStateException e)
            {
              e.printStackTrace();
            }
            catch (IOException e)
            {
              e.printStackTrace();
            }
            // player.prepareAsync();
            player.start();

          }
        });
        layout.setOrientation(LinearLayout.HORIZONTAL);
        layout.addView(text);
        layout.addView(button);
        llPlay.addView(layout);
        
        StartNetTask startNetTask = new StartNetTask(MessageActivity.this, 
            new GetData()
            {
              @Override
              public String getData(String... strings)
              {
                upload(strings[0]);
                return null;
              }
            }, 
            new UICallback()
            {
              @Override
              public void callback(String responseString)
              {
                Util.showToast(MessageActivity.this, getString(R.string.upload_success));
              }
            });
        startNetTask.requestData(filename, false, false);
      }
      return true;
    }
  }

  Handler handler = new Handler()
  {
    public void handleMessage(Message msg)
    {
      // add button
      LinearLayout layout = new LinearLayout(MessageActivity.this);
      TextView text = new TextView(MessageActivity.this);
      Button button = new Button(MessageActivity.this);
      text.setText(msg.getData().getString("username") + ": ");
      button.setText(getString(R.string.play));
      final String PLAY_SOURCE = Constants.BASE_DIR + "/"
          + msg.getData().getString("filename");
      button.setOnClickListener(new OnClickListener()
      {
        @Override
        public void onClick(View v)
        {
          MediaPlayer player = new MediaPlayer();
          if (player.isPlaying())
          {
            player.reset();
          }
          try
          {
            player.setDataSource(PLAY_SOURCE);
            player.prepare();
            // player.prepareAsync();
            player.start();
          }
          catch (Exception e)
          {
            e.printStackTrace();
          }
        }
      });
      layout.setOrientation(LinearLayout.HORIZONTAL);
      layout.addView(text);
      layout.addView(button);
      llPlay.addView(layout);
    }
  };
}
